# -*- coding: utf-8 -*-
import json
import copy
import math
from zc_core.pipelines.helper.catalog_helper import CatalogHelper
from zc_core.model.items import Catalog, ItemData
from obei.model import obeiData
from obei.items import obeiSku


# 解析catalog列表
def parse_catalog(response):
    cats = list()
    json_data = json.loads(response.text).get('data')
    for data in json_data.get('rootNode', []):
        for cat1 in data.get('nodeContants', []):
            cat1_id = cat1.get('code')
            cat1_name = cat1.get('name')
            cat11 = _build_catalog(cat1_id, cat1_name, '', 1)
            cats.append(cat11)
    for data in json_data.get('leafNode').values():
        for cat2 in data:
            cat1_id = cat2.get('parentId')
            cat2_name = cat2.get('title')
            cat2_id = cat2.get('id')
            cat22 = _build_catalog(cat2_id, cat2_name, cat1_id, 2)
            cats.append(cat22)
            for cat3 in cat2.get('children', []):
                cat3_id = cat3.get('id')
                cat3_name = cat3.get('title')
                cat33 = _build_catalog(cat3_id, cat3_name, cat2_id, 3)
                cats.append(cat33)
    return cats


def _build_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 0

    return cat


# 获取按钮权限列表
def parse_menu_code(response):
    json_data = json.loads(response.text)
    return json_data.get('data')


# 维度：三级分页，解析sku列表页数
def parse_total_page(response, page_size):
    json_data = json.loads(response.text)
    totals = math.ceil(int(json_data.get('total')) / page_size)
    if json_data.get('message') == '无搜索商品':
        totals = 1
    return totals


# 维度：品牌，解析sku列表页数
def parse_brand_total_page(response):
    page_json = json.loads(response.text)
    total_page = page_json['result']['pageTotal']

    return total_page


# 解析sku列表
def parse_sku(response, catalog_helper, unit_dict):
    meta = response.meta
    batch_no = meta.get('batchNo')
    catalog3_id = meta.get('catalog3Id')
    json_data = json.loads(response.text).get('data', [])
    skus = list()
    items = list()
    if json.loads(response.text).get('message') == '无搜索商品':
        return [], []
    else:
        for data in json_data:
            sku = obeiSku()
            sku['catalog3Id'] = catalog3_id
            catalog_helper.fill(sku)
            sku['skuId'] = data.get('articleCode')
            sku['skuName'] = data.get('commodityName')
            supplierSkuCode = data.get('commodityCode')
            sku['supplierSkuCode'] = supplierSkuCode
            sku['supplierSkuId'] = supplierSkuCode
            sku['brandCode'] = data.get('brandCode')
            sku['brandName'] = data.get('brandName')
            sku['brandModel'] = data.get('modelCode')
            sku['originPrice'] = data.get('findPrice')
            sku['salePrice'] = data.get('findPrice')
            sku['supplierName'] = data.get('supplierName')
            sku['supplierId'] = data.get('supplierCode')
            sku['batchNo'] = batch_no
            sku['skuImg'] = data.get('commodityMainImage')
            sku['unit'] = unit_dict.get(data.get('unitSite'))
            CatalogHelper().fill(sku)
            result = obeiData()
            result.update(copy.deepcopy(sku))
            items.append(result)
            skus.append(sku)
        # print(skus)
        return skus, items


# 解析ItemData
def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    brandModel = meta.get('brandModel')
    catalog1Name = meta.get('catalog1Name')
    catalog1Id = meta.get('catalog1Id')
    catalog2Name = meta.get('catalog2Name')
    catalog2Id = meta.get('catalog2Id')
    catalog3Name = meta.get('catalog3Name')
    catalog3Id = meta.get('catalog3Id')
    json_data = json.loads(response.text).get('data', {}).get('commodityDetailDto', {})
    result = obeiData()
    # 批次编号
    result['batchNo'] = batch_no
    # 平台商品ID（用于业务系统）
    result['skuId'] = sku_id
    # 平台商品名称（标题） #TODO
    skuName = json_data.get('commodityTaxDto', {}).get('commodityName')
    result['skuName'] = skuName
    result['catalog1Name'] = catalog1Name
    result['catalog1Id'] = catalog1Id
    result['catalog2Name'] = catalog2Name
    result['catalog2Id'] = catalog2Id
    result['catalog3Name'] = catalog3Name
    result['catalog3Id'] = catalog3Id

    supplierSkuId = json_data.get('commodityTaxDto', {}).get('articleNo', '')
    if supplierSkuId:
        # 供应商商品编码
        result['supplierSkuId'] = supplierSkuId
        # 供应商商品编号（无后缀）
        result['supplierSkuCode'] = supplierSkuId

    result['supplierName'] = '自营'
    result['supplierId'] = '00001'
    # 供应商名字
    result['supplierName'] = json_data.get('commodityTaxDto', {}).get('realSupplierName')
    # 供应商ID
    result['supplierId'] = json_data.get('commodityTaxDto', {}).get('realSupplierCode')
    # 主图列表
    skuImg = json_data.get('commodityTaxDto', {}).get('extend4')
    result['skuImg'] = skuImg
    # 品牌名称
    brandName = json_data.get('commodityTaxDto', {}).get('brandName', '')
    # 品牌编号
    brandCode = json_data.get('commodityTaxDto', {}).get('brandCode', '')
    result['brandName'] = brandName
    result['brandCode'] = brandCode
    unit = json_data.get('commodityTaxDto', {}).get('extend2', '')
    result['unit'] = unit
    # 最小起订量
    result['deliveryDay'] = json_data.get('commodityTaxDto', {}).get('preDeliveryDayNum', '')
    # 型号
    brandModel = json_data.get('commodityTaxDto', {}).get('extend3', '')
    result['brandModel'] = brandModel
    return result
